package com.dominator.shiro;

import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.utils.JsonUtils;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.dao.RedisUtil;
import com.dominator.utils.network.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.AnonymousFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;

/**
 * @author gsh
 */
@Slf4j
public class BackendFilter extends AnonymousFilter {

    private static RedisUtil ru = RedisUtil.getRu();

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) {
        ApiUtils.checkFixTime(response);
        return authfilter(request, response);
    }


    public boolean authfilter(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String str = req.getHeader("content-type");
        log.info("content-type:{}", str);
        try {
            req.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String reqUrl = req.getRequestURI();
        // 是否匹配规则
        boolean pass = ignoreUrl(reqUrl);

        String IP = IpUtils.getIpAddr(req);
        log.info("IP:{}", IP);
        Dto dto = JsonUtils.toDto(req.getParameter("paramStr"));
        log.info("uri:{}?paramStr={}", reqUrl, dto);

        if (pass)
            return true;

        //checktoken
        String token = dto.getString("token");
        if (ApiUtils.checkToken(token))
//        if (true)
            return true;

        try {
            response.getWriter().print("{\"code\":\"103\",\"message\":\"token非法\"}");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return false;
        }
    }


    /**
     * 忽略url
     *
     * @param url
     * @return
     */
    private boolean ignoreUrl(String url) {
        // 验证规则
        String[] regEx = {".*login.*",
                ".*upload.*",
                ".*download.*",
                ".*export.*",
                ".*v1.*"
        };
        // 编译正则表达式
        Pattern pattern = null;
        boolean pass = false;
        for (String reg : regEx) {
            // 忽略大小写的写法
            if (Pattern.compile(reg).matcher(url).matches()) {
                pass = true;
                break;
            }
        }
        // 字符串是否与正则表达式相匹配
        return pass;
    }


}
